import json

from django.forms import model_to_dict
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.core import serializers

from .models import Document, Tag


# Create your views here.
def result(data=None, code=200, message="success", kwargs=None):
    json_dict = {'code': code, 'data': data, 'message': message}
    if kwargs and isinstance(kwargs, dict) and kwargs.keys():
        json_dict.update(kwargs)
    # print(json_dict)
    return JsonResponse(json_dict)


# Set Tag class to Document Object
# Get all documents
def handleAllDocuments(request):
    if request.method == 'GET':
        documents = Document.objects.all()
        doc_list = []
        for doc in documents:
            tags = doc.tags.all().values()
            doc_dict = {'docName': doc.docName, 'docFile': str(doc.docFile), 'tags': list(tags)}
            doc_list.append(doc_dict)
        return result(doc_list)
    elif request.method == 'POST':
        doc_name = request.POST.get('docName')
        tagNames = request.POST.get('tags')
        upload_file = request.FILES['file']
        d = Document.objects.create(docName=doc_name, docFile=upload_file)
        for tn in str(tagNames).split(','):
            t = Tag.objects.get_or_create(tagName=tn)[0]
            d.tags.add(t)
            t.tagWeight += 1
            t.save()
        return result("保存成功")
    else:
        HttpResponse({"errMsg": "请求方法错误"})


def getAllTags(request):
    if request.method == "GET":
        tags = Tag.objects.all()
        return result(list(tags.values()))
    else:
        return HttpResponse({"errMsg": "请求方法错误"})